package utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ReadAndWriteFile {
    /**
     *
     * @param path
     * @param charsetName utf-8 gbk
     * @return
     */
    public static List<String> readtFile(String path,String charsetName) {
        List<String> list = new ArrayList<>();
        InputStreamReader read = null;// 考虑到编码格式
        try {
            read = new InputStreamReader(new FileInputStream(path), charsetName);
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = bufferedReader.readLine();
            while ( lineTxt!=null){
                list.add(lineTxt);
                lineTxt = bufferedReader.readLine();
            }
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     *
     * @param path
     * @param content utf-8 gbk
     * @param charsetName
     */
    public static void writeInFile(String path, String content,String charsetName) {
        BufferedWriter writer = null;
        StringBuilder outputString = new StringBuilder();
        try {
            outputString.append(content );
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),charsetName));
            writer.write(outputString.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}
